<template>
    <view>
        <!-- gc_school/pages/shop/addgoods.wxml -->
        <cu-custom bgColor="bgmain" :isBack="true">
            <view slot="content">商品管理</view>
        </cu-custom>
        <view class="box">
            <view class="flex align-center text-bold">
                <!-- <text class="cuIcon-more"></text> -->
                <view class="text-red text-xxl">*</view>
                <view class="text-lg">商品信息</view>
            </view>
            <view class="name text-lg margin-top">名称</view>
            <view style="position: relative">
                <textarea class="textarea" :maxlength="maxTextLen" :value="name" @input="textarea" placeholder-style="color:#D1D1D1;" placeholder="请输入名称"></textarea>
                <view class="left_num">{{ word_num }}/{{ maxTextLen }}</view>
            </view>
            <view class="name text-lg margin-top">副标题</view>
            <view style="position: relative">
                <textarea class="textarea" :maxlength="maxTextLen" v-model="description" placeholder-style="color:#D1D1D1;" placeholder="请输入副标题"></textarea>
                <view class="left_num">{{ word_num }}/{{ maxTextLen }}</view>
            </view>


            <view class="flex justify-between size30 margin-top align-center">
                <view>商品分类</view>
                <picker @change="PickerChange" :value="cate_index" :range="cate" range-key="goods_type_name">
                    <view class="picker text-gray">
                        {{ cate[cate_index].goods_type_name ? cate[cate_index].goods_type_name : '选择分类' }}
                        <text class="cuIcon-right"></text>
                    </view>
                </picker>
            </view>
			<view class="flex size30 margin-top align-center">
			     <view>商品单点时不配送</view>
			     <view class="row" style="margin-left:auto;">
					<switch @change="SwitchB" :class="switchB?'checked':''" :checked="switchB?true:false"></switch>
			     </view>
			
			 </view>
           <view class="flex size30 margin-top align-center">
                <view>商品是否为多规格</view>
                <view class="row" style="margin-left:auto;">
					<switch @change="SwitchA" :class="switchA?'checked':''" :checked="switchA?true:false"></switch>
                </view>

            </view>
			
			<view class="flex size30 margin-top align-center" v-if="switchA" style="margin-bottom: 10rpx;">
			     <view>商品规格</view>
			     <view class="row" style="margin-left:auto;">
			       <!-- 这一行是注掉的  <view class="add addAttr"  @click="showAdd('attributeName')" v-if="!attributeName">添加属性</view> -->
			         <view class="add margin-left" @click="showAdd('specs')" >添加商品规格</view>
			     </view>
			
			 </view>
			 <view class="shuxing" v-if="specs.length !=0 && is_mul == 1"> 
				 <view class="justify-between size30 margin-top align-center" v-if="modalName == 'specs' || specs.length!=0">
				     <view class="row">{{specsName}}
				          <!-- <image
				             class="edit"
				             src="/static/icon/specs/edit.png"
				             mode="scaleToFill"
				             @click="showAdd('specsName')"
				         /> -->
				 
				          <image
				             class="del"
				             src="/static/icon/specs/del.png"
				             mode="scaleToFill"
				             @click="delAll('specs')"
				         />
				     </view>
				     <view class="specs row ">
				         <block v-for="(item,index) in specs" :key="index">
				             <view class="item row margin-right margin-top">
				                 <view class="type">{{item.title}}</view>
				                 <view class="price row">{{item.val}}</view>
				                 <image
				                     class="close"
				                     src="/static/icon/specs/close.png"
				                     mode="scaleToFill"
				                     @click="del('specs',index)"
				                 />
				             </view>
				         </block>
				         <!-- <view class="adds row margin-top" @click="showAdd('specs')" >
				             <view class="cuIcon-add"></view>
				         </view> -->
				     </view>
				 
				 </view>
			 </view>
            
            <view class="justify-between size30 margin-top align-center ts" v-if="attributeName">
                <view class="row">{{attributeName}}
                    <image
                        class="edit"
                        src="/static/icon/specs/edit.png"
                        mode="scaleToFill"
                        @click="showAdd('attributeName')"
                    />

                     <image
                        class="del"
                        src="/static/icon/specs/del.png"
                        mode="scaleToFill"
                        @click="delAll('attribute')"
                    />
                </view>
                 
                <view class="specs row ">
                    <block v-for="(item,index) in attribute" :key="index">
                        <view class="item row margin-right margin-top">
                            <view class="type">{{item}}</view>
                            <!-- <view class="price row">{{item.price}}</view> -->
                            <image
                                class="close"
                                src="/static/icon/specs/close.png"
                                mode="scaleToFill"
                                @click="del('attribute',index)"
                            />
                        </view>
                    </block>
                    <view class="adds row margin-top" @click="showAdd('attribute')">
                        <view class="cuIcon-add"></view>
                    </view>
                </view>
            </view>
            <view class="flex size30 margin-top align-center" v-if="switchA"  style="margin-bottom: 10rpx;">
                <view>商品属性</view>
                <view class="row" style="margin-left:auto;">
                    <!-- <view class="add addAttr" @click="showAdd('attributeName')" v-if="!attributeName">添加属性</view> 这一行是注掉的 -->
                    <view class="add margin-left" @click="showAdd('specsListKey')" >添加商品属性</view>
                </view>
            </view>
            <view class="shuxing"  v-if="specs_list.length !=0"> 
				<block v-for="(item,sindex) in specs_list" :key="sindex" style="border: 1rpx solid red;">
				    <view class="justify-between size30 margin-top align-center">
				        <view class="row">{{item.title}}
				            <image class="edit" src="/static/icon/specs/edit.png" mode="scaleToFill" @click="showAdd('specsListKey',sindex)" />
				            <image class="del" src="/static/icon/specs/del.png" mode="scaleToFill" @click="delAll('specsListKey',sindex)" />
				        </view>
				        <view class="specs row ">
				            <block v-for="(items,index) in item.txt" :key="index">
				                <view class="item row margin-right margin-top">
				                    <view class="type">{{items.name}}</view>
				                    <view class="price row">+{{items.price}}</view>
				                    <image class="close" src="/static/icon/specs/close.png" mode="scaleToFill"
				                        @click="del('specss',index,sindex)" />
				                </view>
				            </block>
				            <view class="adds row margin-top" @click="showAdd('specss',sindex)">
				                <view class="cuIcon-add"></view>
				            </view>
				        </view>
				    
				    </view>
				
				</block>
			</view>
            
            <view class="flex size30 margin-top align-center" v-if="switchA" style="margin-bottom: 10rpx;">
                 <view>单独加料</view>
                 <view class="row" style="margin-left:auto;">
                   <!-- 这一行是注掉的  <view class="add addAttr"  @click="showAdd('attributeName')" v-if="!attributeName">添加属性</view> -->
                     <view class="add margin-left" @click="showAdd('liao')" >单独加料</view>
                 </view>
            
             </view>
             <view class="shuxing" v-if="liao.length !=0">
            	 <view class="justify-between size30 margin-top align-center" v-if="modalName == 'specs' || liao.length!=0">
            	     <view class="row">{{specsName_liao}}
            	          <!-- <image
            	             class="edit"
            	             src="/static/icon/specs/edit.png"
            	             mode="scaleToFill"
            	             @click="showAdd('specsName')"
            	         /> -->
            	 
            	          <image
            	             class="del"
            	             src="/static/icon/specs/del.png"
            	             mode="scaleToFill"
            	             @click="delAll('liao')"
            	         />
            	     </view>
            	     <view class="specs row ">
            	         <block v-for="(item,index) in liao" :key="index">
            	             <view class="item row margin-right margin-top">
            	                 <view class="type">{{item.title}}</view>
            	                 <view class="price row">{{item.val}}</view>
            	                 <image
            	                     class="close"
            	                     src="/static/icon/specs/close.png"
            	                     mode="scaleToFill"
            	                     @click="del('liao',index)"
            	                 />
            	             </view>
            	         </block>
            	        <!-- <view class="adds row margin-top" @click="showAdd('liao')">
            	             <view class="cuIcon-add"></view>
            	         </view> -->
            	     </view>
            	 
            	 </view>
             </view>







            <view class="flex justify-between size30 margin-top align-center" v-if="is_mul == 0">
                <view>商品价格</view>
                <input class="name_input text-right" :value="price" @input="priceFun" placeholder-style="color:#D1D1D1;" placeholder="请输入价格" type="digit" />
            </view>
            <view class="flex justify-between size30 margin-top align-center">
                <view>商品库存</view>
                <input class="name_input text-right" v-model="stock"  placeholder-style="color:#D1D1D1;"
                    placeholder="请输入库存" type="number" />
            </view>
            <view class="flex justify-between size30 margin-top align-center">
                <view>限购数量</view>
                <input class="name_input text-right" v-model="quota" placeholder-style="color:#D1D1D1;" placeholder="请输入商品限购数量，0或不填为不限制"
                    type="number" />
            </view>
     <view class="flex justify-between size30 margin-top align-center">
                    <view>打包费</view>
                    <input class="name_input text-right" v-model="lunchbox" placeholder-style="color:#D1D1D1;" placeholder="请输入打包费"
                        type="digit" />
                </view>
            
            
            <view class="size30 margin-top">商品图片</view>
            <image @click="choose" class="img" :src="img ? img : '/static/images/article/add.png'"></image>

            <view class="size30 margin-top">商品轮播</view>
            <view class="row wrap" style="flex-wrap: wrap;">
                <block v-for="(item,index) in detail_image" :key="index">
                    <image  @click="delBanner(index)" class="img" :src="item" v-if="index<5"></image>
                <!-- @tap="choose" -->
                </block>
                <image @tap="chooseBanner" v-if="detail_image.length<5" class="img" :src="'/static/images/article/add.png'"></image>
            </view>
        </view>

        <view class="flex btn_row justify-between">
            <view @tap="$debounce(submit, 1000, false,2)" data-status="2" class="btn_">存为草稿</view>
            <view @tap="$debounce(submit, 1000, false,1)" data-status="1" class="btn_">发布上架</view>
        </view>

<!-- =='addSpecs' -->
        <view class="cu-modal" :class="modalName?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">
                        <!-- <block v-if="modalName=='specsName'">规格名称</block> -->
                        <block v-if="modalName=='specs'">商品规格</block>
                        <block v-if="modalName=='attributeName'">属性名称</block>
                        <block v-if="modalName=='attribute'">商品属性</block>
                        <block v-if="modalName=='specsListKey'">商品属性名称</block>
                        <block v-if="modalName=='specss'">多规格属性</block>
						<block v-if="modalName=='liao'">单独加料</block>
                    </view>
					<view class="action" @tap="close">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="addModal">
                    <!-- <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specsName'">
                        <view class="key">规格名称</view>
                        <input class="val" v-model="specsName"  placeholder="请输入规格值"  />
                    </view> -->

					<view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specs'" >
                        <view class="key">规格值</view>
                        <input class="val" v-model="formData.title"  placeholder="请输入规格值"  />
                    </view>
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specs'">
                         <view class="key">价格</view>
                        <input class="val"  v-model="formData.val" type="digit" placeholder="请输入价格"  />
                    </view>
                    
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='attributeName'">
                        <view class="key">属性名称</view>
                        <input class="val" v-model="attributeName"  placeholder="请输入属性名称"  />
                    </view>
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='attribute'" >
                        <view class="key">属性值</view>
                        <input class="val" v-model="formData.type"  placeholder="请输入属性值"  />
                    </view>
                    <!-- <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='attribute'">
                        <view class="key">属性金额</view>
                        <input class="val" v-model="formData.price" placeholder="请输入属性金额" />
                    </view> -->

                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specsListKey'">
                        <view class="key">商品属性</view>
                        <input class="val" v-model="formData.title" placeholder="请输入属性名称" />
                    </view>
					<view class="item margin-bottom margin-lr flex padding-lr" v-if="modalName=='specsListKey'" style="display: flex;justify-content: space-between;">
					    
					    <view class="key">是否多选</view>
						<checkbox-group class="block" @change="CheckboxChange">
					      <checkbox :class="checkbox[0].checked?'checked':''"  :checked="checkbox[0].checked?true:false" value="A"></checkbox>
					    </checkbox-group>
					</view>

                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specss'">
                        <view class="key">规格值</view>
                        <input class="val" v-model="formData.name" placeholder="请输入规格值" />
                    </view>
                    <!-- <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='specss'">
                        <view class="key">价格</view>
                        <input class="val" v-model="formData.price" type="digit" placeholder="请输入价格" />
                    </view> -->

                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='liao'" >
                        <view class="key">规格值</view>
                        <input class="val" v-model="formData.title"  placeholder="请输入规格值"  />
                    </view>
                    <view class="item margin-bottom margin-lr flex padding-lr" v-show="modalName=='liao'">
                         <view class="key">价格</view>
                        <input class="val"  v-model="formData.val" type="digit" placeholder="请输入价格"  />
                    </view>


                    <!-- <view class="tips row padding-left" v-if="modalName=='specsName'">温馨提醒：基础规格为产品的基础价格，例如:大、中、小碗</view> -->
                    <view class="tips row padding-left" v-show="modalName=='attributeName'">温馨提醒： 属性不影响价格</view>
                    <view class="tips row padding-left" v-show="modalName=='specsListKey'">温馨提醒：例如(甜度，辣度等)</view>
					<!-- <view class="tips row padding-left" v-show="modalName=='specsListKey'">温馨提醒： 多规格为基础规格额外的规格例如：可乐、加面、加某种佐料</view> -->

                    
				</view>
                <view class="cu-bar bg-white">
					<view class="action btns">
						<button class="cu-btn close" @tap="close">取消</button>
						<button class="cu-btn enter" @tap="addSpecs">确定</button>
					</view>
				</view>
			</view>
		</view>


     </view>
</template>

<script>
// gc_school/pages/shop/addgoods.js
import siteInfo from '@/siteinfo.js';
// import list from '../../../unpackage/dist/dev/mp-weixin/gc_school/pages/canteen/list';
var app = getApp();
export default {
    data() {
        return {
            word_num: 0,
            maxTextLen: 20,
            cate: [],
            cate_index: -1,
            img: '',
            name: '',
            price: '',
            cate_id: 0,
            id: 0,
            word_left: '',
            modalName:'',
            formData: {
               
            },
            specs:[
                // {type:"大份", price:"20"},
                // {type:"中份", price:"18"},
                // {type:"小份", price:"15"}
            ],
			liao:[],
            specsName:"规格",
            attribute:[
                // "微辣","不辣"
            ],
            attributeName:"",
            stock:"",
            quota:"",
            specs_list:[],//商品属性2
            si:-1,
            detail_image:[],
            description:"",
            lunchbox:0,
			switchA:'',
			switchB:'',
			specsName_liao:'单独加料',
            checkbox: [{
                    value: 'A',
                    checked: false
                }],
			alone_type:'0',//商品单点时是否配送,
			is_mul:'0'
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        // this.getCate();

        if (options.id) {
            this.setData({
                id: options.id
            });
            this.getInfo();
        }else{
            this.getCate()

        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {
    // }
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ 
    methods: {
		//是否多选
		CheckboxChange(e){
			console.log(e)
			 var items = this.checkbox,
			values = e.detail.value;
			 for (var i = 0, lenI = items.length; i < lenI; ++i) {
			        items[i].checked = false;
					this.formData.is_mul = 0
			        for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
			            if (items[i].value == values[j]) {
			                items[i].checked = true;
							this.formData.is_mul = 1
			                break
			            }
			        }
			    }
			
		},
		//商品多规格开关
		SwitchA(e) {
		    this.switchA = e.detail.value
			if(this.switchA == true){
				this.is_mul = 1
			}else{
				this.is_mul = 0
			}
		},
		//商品多规格开关
		SwitchB(e) {
		    this.switchB = e.detail.value
			if(this.switchB == true){
				this.alone_type = 1
			}else{
				this.alone_type = 0
			}
		},
        showAdd(name,si=-1){
            // if (name == "specsListKey" && this.specs.length==0) {
            //     this.tips.error("请先添加基础规格")
            //     return false
            // }


            this.modalName=name
            this.si=si
            // specsListKey
            // console.log(this.specs_list[si].name);
			if(si > -1){
				this.checkbox[0].checked = this.specs_list[si].is_mul == 1 ? true : 0
			}
            try {
                if (this.specs_list[si].name && name == "specsListKey") {
                    this.formData = {
                        type: this.specs_list[si].name
                    }
                }
            } catch (error) {
                
            }
           
        },

        close(){
            this.modalName=""
             this.formData = {
                 type: "",
                 price: ""
             }
            // setTimeout(() => {
            //     this.formData={
            //         type:"",
            //         price:""
            //     }
            // },1500);
            
         },
        del(type="",index,sindex=-1){

            if (sindex>-1) {
                let item = this.specs_list[sindex]
                item.txt.splice(index,1)
                console.log(item);
                this.specs_list[sindex] = item
            }else{
                this[type].splice(index, 1)

            }
         },

        delAll(type,i=-1){
            if (type =="specsListKey") {
                this.specs_list.splice(i,1)
            }else{
                // this[type + "Name"] = ''
				this.modalName = ''
                this[type] = []
            }
        },
        addSpecs(){
             switch (this.modalName) {
                case "specs":
                    // if (!this.formData.type) {
                    //     this.tips.error("规格值不能为空") 
                    //     break;
                    // }
                    if (!this.formData.val) {
                        this.tips.error("规格价格不能为空") 
                        break;
                    }
                    if (!isFinite(this.formData.val)) {
                        this.tips.error("请输入有效价格") 
                        break;

                    }
                    this.formData.val = Number(this.formData.val).toFixed(2);
                    this[this.modalName].push(this.formData)
                    this.close()

                    break;
				case "liao":
				    // if (!this.formData.type) {
				    //     this.tips.error("规格值不能为空") 
				    //     break;
				    // }
				    if (!this.formData.val) {
				        this.tips.error("规格价格不能为空") 
				        break;
				    }
				    if (!isFinite(this.formData.val)) {
				        this.tips.error("请输入有效价格") 
				        break;
				
				    }
				    this.formData.val = Number(this.formData.val).toFixed(2);
				    this[this.modalName].push(this.formData)
				    this.close()
				
				    break;
                case "attribute":
                    if (!this.formData.title) {
                        this.tips.error("属性值不能为空") 
                        break;
                    }
                    // this[this.modalName].push(this.formData)
                     this[this.modalName].push(this.formData.type)
                    this.close()

                     break;
                case "specsListKey":
                     if (!this.formData.title) {
                         this.tips.error("属性值不能为空")
                         break;
                     }
                     if (this.si>-1) {
						 // this.formData.is_mul = this.specs_list[this.si].is_mul
						 // if(this.specs_list[this.si].is_mul == 1){
							//  this.checkbox[0].checked = true
						 // }else{
							//  this.checkbox[0].checked = false
						 // }
                         this.specs_list[this.si].title = this.formData.title
						 
						 this.specs_list[this.si].is_mul = this.checkbox[0].checked == true ? 1 : 0, 
						 
						 console.log(123, this.checkbox[0].checked)
                    } else {
                         this.specs_list.push({
                             title: this.formData.title,
							 is_mul:this.checkbox[0].checked  ? 1 :0,
                             txt: []
                         })
                    }
                    
                    //  this[this.modalName].push(this.formData)
                     this.close()

                     break;
                case "specss":
                     if (!this.formData.name) {
                         this.tips.error("规格值不能为空")
                         break;
                     }
                     // if (!this.formData.price) {
                     //     this.tips.error("规格价格不能为空")
                     //     break;
                     // }
                     // if (!isFinite(this.formData.price)) {
                     //     this.tips.error("请输入有效价格")
                     //     break;

                     // }
                     // this.formData.price = Number(this.formData.price).toFixed(2);
					 this.formData.price = 0;

                     this.specs_list[this.si].txt = [
                         ... this.specs_list[this.si].txt,
                         this.formData
                     ]
                     console.log(this.specs_list);
                     this.close()

                     break;

                    
                default:
                    this.close()

                     break;

             }
            
          
             
         },
        getInfo() {
            var that = this;
            app.globalData.util.request({
                url: 'ZhGoodss/view',
				method: 'GET',
                data: {
                    id: that.id,
					s_id: uni.getStorageSync('schoolId')
                },

                success(res) {
					if(res.data.data.is_mul == 1){
						console.log(6666,res.data.data);
											let specs = res.data.data.specs_new.map(item =>{
												return {
													val: item.SalesPrice, // 将SalesPrice的值赋给新的val键  
													title: item.specsName, // 将specsName的值赋给新的title键 
												}
											})
											let liao = res.data.data.materia.map(item =>{
												return {
													val: item.SalesPrice, // 将SalesPrice的值赋给新的val键  
													title: item.materialName, // 将specsName的值赋给新的title键  
												}
											})
						let specs_list = res.data.data.attr.map(item =>{
							return {
												  is_mul:item.is_mul,
								  title: item.attrName,  // 将SalesPrice的值赋给新的val键  
								  txt: item.attrStr,  // 将specsName的值赋给新的title键  
							}
						})
											that.specs = specs
											that.liao = liao
											that.specs_list = specs_list
					}
                   
					// that.$forceUpdate();
					// this.$forceUpdate()
					// console.log(7777,that.specs);
					console.log(8888,res.data.data.detail_image);
                    that.setData({
                        name: res.data.data.goods_name,
                        price: res.data.data.price,
                        img: res.data.data.goods_img,
                        cate_id: res.data.data.goods_type_id,
                        word_num: res.data.data.goods_name.length,
                        stock: res.data.data.stock,
                        quota: res.data.data.quota,
                        description:res.data.data.description,
                        detail_image:res.data.data.detail_image.split(",")||[],
                        lunchbox:res.data.data.lunchbox,
						is_mul:res.data.data.is_mul,
						alone_type:res.data.data.alone_type,
						// liao:liao,
						// specs_list:res.data.data.attr,
						// specs:that.specs,
						switchA:res.data.data.is_mul == 1 ? true:false,
						switchB:res.data.data.alone_type == 1 ? true:false
                    });
                    try {
      //                   that.specs = JSON.parse(res.data.data.specs).list || []
      //                   that.specsName = JSON.parse(res.data.data.specs).name || ""
      //                   that.attribute = JSON.parse(res.data.data.attribute).list || []
      //                   that.attributeName = JSON.parse(res.data.data.attribute).name || ""
      //                   that.specs = specs
						// that.liao = liao

                    } catch (error) {
                        
                    }
                        // that.specs =  []

                    // try {
                    //     that.specs_list=JSON.parse(res.data.data.specs_list)  
                    // } catch (error) {
                    //     that.specs_list =[]
                    // }
                    that.getCate()
                    
                }
            },true);
        },

        getCate() {
            var that = this;
            app.globalData.util.request({
                url: 'ZhGoodsType/index',
				method: 'GET',
                data: {
                    s_id: uni.getStorageSync('schoolId')
                },

                success(res) {
                    that.cate = res.data.data.list
                    // that.cate_id = res.data.data.list[0].goods_type_id
                    for (var i = 0; i < res.data.data.list.length; i++) {
                        if (res.data.data.list[i].goods_type_id == that.cate_id) {
                            that.setData({
                                cate_index: i
                            });
                        }
                    }
                }
            },true);
        },

        //分类选择
        PickerChange(e) {
            this.setData({
                cate_index: e.detail.value,
                cate_id: this.cate[e.detail.value].goods_type_id
            });
        },

        //图片上传
        choose() {
           var that = this;
		   console.log(123)
           uni.chooseImage({
               count: 1,
               success(res) {
				   console.log(res)
                   that.uploadimg(res.tempFilePaths, 'ImgPost'); // wx.hideLoading({})
               }
           });
        },

        async chooseBanner(){
            var that = this;
            uni.chooseImage({
                count:5-this.detail_image.length,
                async success(res) {
                    for (let i = 0; i <  res.tempFilePaths.length; i++) {
                        const element =  res.tempFilePaths[i];
                        let ress= await that.uploadimg([element], 'detail_image'); 
                        // wx.hideLoading({})
                        console.log(ress);
                    }

                }
            });
        },
        delBanner(i){
            console.log(i);
            this.detail_image.splice(i,1)

        },
        
        uploadimg (data, method, type) {
			console.log(data)
            console.log(method);
            uni.showLoading({
                title: '上传中...',
                mask: true
            });
            var that = this; // var count = that.data.addedCount + data.length;
            var count = that.addedCount;
            // for (var i = 0; i < data.length; i++) {
                return new Promise((resolve, reject) =>{
                    uni.uploadFile({
                        url: siteInfo.url+'Base/upload',
                        filePath: data[0],
                        header:{
                            'Authorization':uni.getStorageSync('token')
                        },
                        name: 'file',
                        formData: {
                            'wxapp_id':siteInfo.uniacid
                        },
                        success: (resp) => {
                            var pic = JSON.parse(resp.data);
                            console.log("打印",pic)
                            uni.hideLoading({});

                            if (pic.status == 200) {
                                resolve(pic.data)
                                if (method=="detail_image") {
                                    console.log(pic);
                                    this.detail_image.push(pic.data)
                                    return
                                }
                                that.setData({
                                    addedCount: count,
                                    img: pic.data
                                });
                                uni.hideLoading({});

                            } else {
                                uni.showToast({
                                    title: pic.msg,
                                    icon: 'none'
                                });
                            }
                        }
                    });
                })

            // }
        },

        priceFun(e) {
            this.setData({
                price: e.detail.value
            });
        },

        textarea(e) {
            var value = e.detail.value.replace(/\s+/g, '');
            this.setData({
                word_num: value.length,
                word_left: 20 - value.length,
                name: value
            });
        },

        submit(e) {
            console.log( parseInt(this.stock));
            if (!( parseInt(this.stock)>=0)) {
                this.tips.tips("库存无效！")

                return false;
            }
            if (!this.name) {
                app.globalData.util.message('请输入名称', '', 'error');
                return false;
            }

            if (this.price <= 0 && this.is_mul == 0) {
                app.globalData.util.message('请输入价格', '', 'error');
                return false;
            }
			if(!this.specs.length > 0 && this.is_mul == 1){
				app.globalData.util.message('请添加商品规格', '', 'error');
				return false;
			}

            if (!this.cate_id) {
                app.globalData.util.message('请选择分类', '', 'error');
                return false;
            }
          

           
            if (!this.img) {
                app.globalData.util.message('请上传图片', '', 'error');
                return false;
            }
            // let specs=JSON.stringify({
            //     name:this.specsName,
            //     list:this.specs
            // })
			let specs=JSON.stringify(this.specs)
			let specs_list=JSON.stringify(this.specs_list)
			let liao=JSON.stringify(this.liao)
            let attribute=JSON.stringify({
                name:this.attributeName,
                list:this.attribute
            })
			// 属性1
            if (this.specs.length==0) {
                specs=""
            }
			// 属性2
            if (this.specs_list.length==0) {
                specs_list=""
            }
            //属性3
            if (this.liao.length==0) {
                liao=""
            }
             
			if(!this.id){
				uni.showLoading({
					title: '发布中…'
				});
				app.globalData.util.request({
				    url: 'ZhGoodss/add',
				    data: {
				        goods_img: this.img,
				        goods_name: this.name,
				        price: this.price,
				        goods_type_id: this.cate_id,
				        s_id: uni.getStorageSync('schoolId'),
				        status: e,
                        specs,
                        attribute,
                        stock: this.stock,
                        quota: this.quota,
                        specs_list: JSON.stringify(this.specs_list),
						specs: JSON.stringify(this.specs),//商品属性1
						attr: JSON.stringify(this.specs_list),//商品属性2
						materia: JSON.stringify(this.liao),//商品属性3
                        detail_image:this.detail_image.join(","),
                        description:this.description,
                        lunchbox:this.lunchbox,
						alone_type:this.alone_type ,//单点时是否配送,
						is_mul:this.is_mul
				    },
				
				    success(res) {
				        if (res.data.status == 200) {
				            uni.showToast({
				                title: res.data.message
				            });
				            setTimeout(function () {
                                uni.navigateBack({ delta: 1 })
                                return;
				                uni.redirectTo({
				                    url: '/gc_school/pages/shop/goods'
				                });
				            }, 1000);
				        }
						uni.hideLoading();
				    }
				},true);
			}else {
				app.globalData.util.request({
				    url: 'ZhGoodss/update',
				    data: {
				        goods_img: this.img,
				        goods_name: this.name,
				        price: this.price,
				        goods_type_id: this.cate_id,
				        s_id: uni.getStorageSync('schoolId'),
				        status: e,
						id: this.id,
                        specs,
                        attribute,
                        stock: this.stock,
                        quota: this.quota,
                        specs_list: JSON.stringify(this.specs_list),
                        detail_image: this.detail_image.join(","),
                        description: this.description,
                        lunchbox:this.lunchbox,
						specs: JSON.stringify(this.specs),//商品属性1
						attr: JSON.stringify(this.specs_list),//商品属性2
						materia: JSON.stringify(this.liao),//商品属性3
						alone_type:this.alone_type ,//单点时是否配送,
						is_mul:this.is_mul
                        // alone_type:this.
					
                        // specs_list: JSON.stringify(
                        //     [
                        //         { 
                        //             "name": "饮品", 
                        //             "list": [
                        //                 { "type": "可乐", "price": "4.00" }, 
                        //                 { "type": "加奶", "price": "5.00" },
                        //                 { "type": "冰峰", "price": "4.00" }
                        //             ] 
                        //         }, 
                        //         { 
                        //             "name": "加料", 
                        //             "list": [
                        //                 { "type": "加粉", "price": "5.00" }, 
                        //                 { "type": "加蘑菇", "price": "3.00" },
                        //                 { "type": "加鸡腿", "price": "6.00" }
                        //             ] 
                        //         },
                        //         {
                        //             "name": "打包方式(必选，不选下单无效)",
                        //             "list": [
                        //                 { "type": "塑料袋袋", "price": "0.00" },
                        //                 { "type": "打包盒(中)", "price": "2.00" },
                        //                 { "type": "打包盒(豪华)", "price": "6.00" }
                        //             ]
                        //         }
                        //     ]
                        // )
                        
                        
                        
                        

				    },
				
				    success(res) {
				        if (res.data.status == 200) {
				            uni.showToast({
				                title: res.data.message
				            });
				            setTimeout(function () {
                                uni.navigateBack({ delta: 1 })
                                return ;
				                uni.redirectTo({
				                    url: '/gc_school/pages/shop/goods'
				                });
				            }, 1000);
				        }
				    }
				},true);
			}

            
        }
    }
};
</script>
<style>
/* gc_school/pages/shop/addgoods.wxss */
page {
    background: #f9f9f9;
}
.box {
    background: white;
    border-radius: 10rpx;
    margin: 30rpx;
    padding: 30rpx;
}
.textarea {
    background: #f9f9f9;
    border-radius: 10rpx;
    width: 100%;
    height: 150rpx;
    margin-top: 20rpx;
    padding: 20rpx;
}
.left_num {
    position: absolute;
    right: 20rpx;
    bottom: 20rpx;
    color: #d1d1d1;
}
.size30 {
    font-size: 30rpx;
}
.name_input {
    width: 50%;
}
.img {
    margin-top: 30rpx;
    width: 200rpx;
    height: 200rpx;
    margin-right: 10rpx;
}
.btn_row {
    margin: 70rpx 50rpx 30rpx;
}
.btn_:first-child {
    background: #00bb69 !important;
}
.btn_ {
    width: 300rpx;
    height: 80rpx;
    line-height: 80rpx;
    background: #ff6344;
    color: white;
    text-align: center;
    border-radius: 10rpx;
    font-size: 30rpx;
}
.shuxing{
	border: 1rpx solid #eee;
	padding: 10rpx;
	border-radius: 24rpx;
}
</style>
<style lang="scss">
    @import "./addgoods.scss";
</style>
